import axios from 'axios'
import Vue from 'vue'
import { getToken } from '@/utils/auth'

// create an axios instance
const service = axios.create({
  timeout: 120000, // request timeout
})

// request interceptor
service.interceptors.request.use(
  config => {
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = `Bearer ${token}`
    }
    return config
  },
  error => {
    console.log(error) // for debug
    Promise.reject(error)
  },
)

// response interceptor
service.interceptors.response.use(
  response => {
    let res = response.data
    if (res.status == undefined) return res
    if (res.status === true) {
      return res.data
    } else {
      return Promise.reject(res)
    }
  },
  error => {
    return Promise.reject(error)
  },
)

export default function request(url, data, method, donotAutoShowError) {
  data = data || {}
  method = (method || 'get').toLowerCase()
  var config = {
    url,
    method,
  }
  if (method === 'get') {
    config.params = data
  } else {
    config.data = data
  }
  return new Promise((resolve, reject) => {
    service(config)
      .then(r => {
        resolve(r)
      })
      .catch(e => {
        if (!donotAutoShowError) {
          Vue.prototype.$message({
            message: e.message || 'Unknown Error',
            type: 'error',
            duration: 5 * 1000,
          })
        }
        reject(e)
      })
  })
}
